package com.yuexun.dhdoctor.module.email.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.email.bean.MailFileDataBean;
import com.yuexun.dhdoctor.util.FileUtils;
import com.yuexun.dhdoctor.widget.HttpDownloader;

import org.kymjs.kjframe.ui.ViewInject;

import java.util.ArrayList;

/**
 * Created by work-jx on 2016/8/3.
 */
public class DraftEdtFileAdapter  extends BaseAdapter {
    private static final String FILE_STATE_KEY = "fileState";   //查看下载状态键
    private static final String FILE_PATH_KEY = "filePath";   //文件路径键

    private Context mContext;
    private ArrayList<MailFileDataBean> beanList;

    public DraftEdtFileAdapter(Context mContext, ArrayList<MailFileDataBean> beanList) {
        this.mContext = mContext;
        this.beanList = beanList;
    }

    @Override
    public int getCount() {
        return null == beanList ? 0 : beanList.size();
    }

    @Override
    public Object getItem(int position) {
        return null == beanList ? null : beanList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(null == convertView) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_attachment, parent, false);
            holder = new ViewHolder();
            holder.filenameAndSizeT = (TextView)convertView.findViewById(R.id.tv_filename_and_fileSize);
            holder.downloadB = (Button)convertView.findViewById(R.id.btn_download);
            holder.progressBar = (ProgressBar)convertView.findViewById(R.id.progressBar);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }

        final MailFileDataBean bean = beanList.get(position);
        SpannableStringBuilder styleStringBuilder = new SpannableStringBuilder(bean.getFileName() + "(" + new java.text.DecimalFormat("#.00").format(Double.valueOf(bean.getFileSize())/1024.00) + "KB)");
        styleStringBuilder.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.txt_black2)), 0,bean.getFileName().length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        holder.filenameAndSizeT.setText(styleStringBuilder);
        final FileUtils fileUtils = new FileUtils(mContext);
        final String [] filenames = bean.getFileName().split("\\.");
        if(fileUtils.isFileExist(AppConfig.FILE_CONTENT+bean.getFileUuid()+"."+filenames[filenames.length-1])) {
            holder.downloadB.setText("查看");
        }
        else {
            holder.downloadB.setText("下载");
        }
        holder.downloadB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (!fileUtils.isFileExist(AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1])) {
                            HttpDownloader httpDownLoader = new HttpDownloader(mContext);
                            handler.sendEmptyMessage(0);
                            int result = httpDownLoader.downfile(AppConfig.WEB_FILE + bean.getFileUuid(),
                                    AppConfig.FILE_CONTENT, bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                            if (result == 0) {
                                handler.sendEmptyMessage(1);
                                Intent intent = fileUtils.openFile(FileUtils.getSDPATH() + AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                                try {
                                    mContext.startActivity(intent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else if (result == 1) {
                                Intent intent = fileUtils.openFile(FileUtils.getSDPATH() + AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                                try {
                                    mContext.startActivity(intent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else if (result == -1) {
                                handler.sendEmptyMessage(2);
                            }
                        } else {
                            Intent intent = fileUtils.openFile(FileUtils.getSDPATH() + AppConfig.FILE_CONTENT + bean.getFileUuid() + "." + filenames[filenames.length - 1]);
                            try {
                                mContext.startActivity(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        });

        return convertView;
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    ViewInject.toast("开始下载...");
                    break;
                case 1:
                    ViewInject.toast("下载完成");
                    break;
                case 2:
                    ViewInject.toast("下载失败");
                    break;
            }
        }

    };

    private class ViewHolder {
        public TextView filenameAndSizeT;
        public Button downloadB;
        public ProgressBar progressBar;
    }

    private enum FileStateEnum {
        //0-未知 1-下载 2-查看
        UNKNOWN,
        DOWNLOAD,
        LOOK;

        public static FileStateEnum valueOf(int value) {
            if(value <0  || value > values().length) {
                return getDefault();
            }

            return values()[value];
        }

        public static FileStateEnum getDefault() {
            return UNKNOWN;
        }
    }
}
